package cn.zhagzheguo.xk.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.zhagzheguo.xk.dao.CommentDao;
import cn.zhagzheguo.xk.dao.CourseSelectDao;
import cn.zhagzheguo.xk.model.Comment;
import cn.zhagzheguo.xk.model.Course;
import cn.zhagzheguo.xk.status.CommentStatus;
import cn.zhagzheguo.xk.status.CommonStatus;
import cn.zhagzheguo.xk.util.DateFormatUtil;

@RequestMapping("/comment")
@Controller
public class CommentController {

	@Autowired
	private CommentDao cd;

	@Autowired
	private CourseSelectDao csDao;

	@RequestMapping("/course")
	@ResponseBody
	public List<Comment> getCourseComments(@RequestParam("course_id") int id) {
		List<Comment> list = cd.getAllByCourseId(id);
		System.out.println("/comment/course list.size=" + list.size() + ",list=" + list.toString());
		return list;
	}

	@RequestMapping("/add")
	@ResponseBody
	public String addComment(Comment comment) {

		int stu_id = comment.getStu_id();
		int course_id = comment.getCourse_id();

		// 查看是否已选择该课程
		List<Course> list = csDao.getBriefByStuId(stu_id);
		boolean isSelected = false;
		for (Course c : list) {
			if (c.getId() == course_id) {
				isSelected = true;
				break;
			}
		}
		if (!isSelected) {
			return CommentStatus.NOT_SELECT;
		}

		// 查看评论内容是否符合规则
		String content = comment.getContent();
		if (content.length() >= 100 || content.length() < 1) {
			return CommentStatus.WRONG_CONTENT;
		}

		comment.setDate(DateFormatUtil.format(new Date()));
		comment.setGreat(0);
		System.out.println("/comment/add  comment=" + comment.toString());
		int result = cd.insert(comment);
		if (result == CommonStatus.SUCCESS) {
			return CommentStatus.SUCCESS;
		}

		return CommentStatus.FAIL;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String deleteComment(int comment_id) {
		int result = cd.delete(comment_id);
		if (result == CommonStatus.SUCCESS) {
			return "success";
		} else {
			return "fail";
		}
	}

	/***********************************/
	public void setCd(CommentDao cd) {
		this.cd = cd;
	}

	public void setCsDao(CourseSelectDao csDao) {
		this.csDao = csDao;
	}

}
